<template>
    <div class='container'>
        <!-- 页面头部 -->
        <page-header title="编辑作品" @heightChange="handleHeaderHeightChange" />

        <!-- 表单区域 -->
        <view class="form-section">
            <!-- 作品图片上传 -->
            <view class="upload-section">
                <view class="upload-title">作品图片</view>
                <view class="upload-area" @click="handleImageUploadClick">
                    <image v-if="formData.image" class="uploaded-image" :src="formData.image" mode="aspectFill" />
                    <view v-else class="upload-placeholder">
                        <uni-icons type="camera" size="40" color="#ccc"></uni-icons>
                        <view class="upload-text">点击上传图片</view>
                    </view>
                </view>
            </view>

            <!-- 基本信息 -->
            <view class="form-group">
                <view class="form-label">作品标题</view>
                <input class="form-input" placeholder="请输入作品标题" v-model="formData.title" maxlength="50" />
                <view class="form-tip">{{ formData.title.length }}/50</view>
            </view>

            <view class="form-group">
                <view class="form-label">作品分类</view>
                <view class="category-selector" @click="handleCategorySelectClick">
                    <view class="selected-category">{{ formData.category || '请选择分类' }}</view>
                    <uni-icons type="right" size="16" color="#666"></uni-icons>
                </view>
            </view>

            <view class="form-group">
                <view class="form-label">作品描述</view>
                <textarea class="form-textarea" placeholder="请详细描述您的作品..." v-model="formData.description"
                    maxlength="500" />
                <view class="form-tip">{{ formData.description.length }}/500</view>
            </view>

            <!-- 作品链接 -->
            <view class="form-group">
                <view class="form-label">作品链接（可选）</view>
                <input class="form-input" placeholder="请输入作品链接" v-model="formData.link" />
            </view>

            <!-- 标签设置 -->
            <view class="form-group">
                <view class="form-label">作品标签</view>
                <view class="tags-section">
                    <view class="tags-input">
                        <input class="tag-input" placeholder="输入标签后按回车" v-model="tagInput" @confirm="handleAddTag" />
                    </view>
                    <view class="tags-list">
                        <view class="tag-item" v-for="(tag, index) in formData.tags" :key="index">
                            <view class="tag-text">{{ tag }}</view>
                            <view class="tag-delete" @click="handleDeleteTag(index)">
                                <uni-icons type="close" size="12" color="#fff"></uni-icons>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 隐私设置 -->
            <view class="form-group">
                <view class="form-label">隐私设置</view>
                <view class="privacy-options">
                    <view class="privacy-item" @click="handlePrivacyChange('public')">
                        <view class="privacy-radio" :class="{ active: formData.privacy === 'public' }"></view>
                        <view class="privacy-text">公开作品</view>
                    </view>
                    <view class="privacy-item" @click="handlePrivacyChange('private')">
                        <view class="privacy-radio" :class="{ active: formData.privacy === 'private' }"></view>
                        <view class="privacy-text">仅自己可见</view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 预览区域 -->
        <view class="preview-section" v-if="showPreview">
            <view class="preview-header">
                <view class="preview-title">作品预览</view>
                <view class="preview-toggle" @click="handlePreviewToggle">
                    <view>隐藏预览</view>
                </view>
            </view>
            <view class="preview-content">
                <view class="preview-work">
                    <image v-if="formData.image" class="preview-image" :src="formData.image" mode="aspectFill" />
                    <view class="preview-info">
                        <view class="preview-title-text">{{ formData.title || '作品标题' }}</view>
                        <view class="preview-author">作者：{{ userInfo.name }}</view>
                        <view class="preview-desc">{{ formData.description || '作品描述' }}</view>
                        <view class="preview-tags">
                            <view class="preview-tag" v-for="(tag, index) in formData.tags" :key="index">
                                {{ tag }}
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-section">
            <view class="action-buttons">
                <button class="preview-btn" @click="handlePreviewToggle">
                    <view>{{ showPreview ? '隐藏预览' : '预览作品' }}</view>
                </button>
                <button class="save-btn" @click="handleSaveButtonClick">
                    <view>{{ isSubmitting ? '保存中...' : '保存作品' }}</view>
                </button>
            </view>
        </view>

        <!-- 底部导航栏 -->
        <page-bottom pageUrl="/pages-vote/Index" @navClick="handleTabClick" @heightChange="handleBottomHeightChange" />
    </div>
</template>

<script>
// 结构
import {
    defineComponent,
    onMounted,
    ref,
    reactive,
    computed
} from 'vue';
// 模块化
import PageHeader from '@/components/PageHeader.vue';
import PageBottom from '@/components/PageBottom.vue';

export default defineComponent({
    name: 'EntryEdit', // 组件名称
    props: {
        // 接收父组件数据

    },
    components: {
        PageHeader,
        PageBottom
    },
    // 主要是组件内交互事件
    setup(props, ctx) {
        // 这里没有this,直接使用props里数据
        // 进行数据的定义和初始化。object style interactive
        onMounted(() => { });

        // ===== 响应式对象 =====
        // 头部高度相关数据
        const headerHeight = ref(0);
        const bottomHeight = ref(0);

        // 表单数据
        const formData = ref({
            title: '',
            category: '',
            description: '',
            image: '',
            link: '',
            tags: [],
            privacy: 'public'
        });

        // 标签输入
        const tagInput = ref('');

        // 预览状态
        const showPreview = ref(false);

        // 提交状态
        const isSubmitting = ref(false);

        // 用户信息
        const userInfo = ref({
            name: '张三',
            avatar: '/static/images/avatar-default.jpg'
        });

        // 分类选项
        const categoryOptions = ref([
            '技术创新',
            '产品设计',
            '服务改进',
            '创意设计',
            '管理优化',
            '其他'
        ]);

        // ===== 方法函数 =====
        // 处理头部高度变化
        const handleHeaderHeightChange = (heightInfo) => {
            headerHeight.value = heightInfo.totalHeaderHeight;
        };

        // 处理底部高度变化
        const handleBottomHeightChange = (heightInfo) => {
            bottomHeight.value = heightInfo.totalBottomHeight;
        };

        // 处理图片上传点击
        const handleImageUploadClick = () => {
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
                    formData.value.image = res.tempFilePaths[0];
                },
                fail: (err) => {
                    uni.showToast({
                        title: '选择图片失败',
                        icon: 'none'
                    });
                }
            });
        };

        // 处理分类选择点击
        const handleCategorySelectClick = () => {
            uni.showActionSheet({
                itemList: categoryOptions.value,
                success: (res) => {
                    formData.value.category = categoryOptions.value[res.tapIndex];
                }
            });
        };

        // 处理添加标签
        const handleAddTag = () => {
            if (tagInput.value.trim() && formData.value.tags.length < 5) {
                formData.value.tags.push(tagInput.value.trim());
                tagInput.value = '';
            } else if (formData.value.tags.length >= 5) {
                uni.showToast({
                    title: '最多添加5个标签',
                    icon: 'none'
                });
            }
        };

        // 处理删除标签
        const handleDeleteTag = (index) => {
            formData.value.tags.splice(index, 1);
        };

        // 处理隐私设置变更
        const handlePrivacyChange = (privacy) => {
            formData.value.privacy = privacy;
        };

        // 处理预览切换
        const handlePreviewToggle = () => {
            showPreview.value = !showPreview.value;
        };

        // 处理保存按钮点击
        const handleSaveButtonClick = () => {
            if (!validateForm()) {
                return;
            }

            isSubmitting.value = true;

            // 模拟保存过程
            setTimeout(() => {
                isSubmitting.value = false;
                uni.showToast({
                    title: '保存成功',
                    icon: 'success'
                });

                // 返回上一页
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
            }, 2000);
        };

        // 处理底部导航点击
        const handleTabClick = (item) => {
            console.log('切换到:', item.path);
        };

        // ===== 生命周期钩子 =====
        onMounted(() => {
            // 可以在这里加载编辑数据
            loadEditData();
        });

        // 加载编辑数据
        const loadEditData = async () => {
            try {
                // TODO: 调用实际接口获取编辑数据
                // const res = await getWorkEditData(this.$route.query.id);
                // formData.value = res.data;
            } catch (error) {
                console.error('加载编辑数据失败:', error);
                uni.showToast({
                    title: '加载数据失败',
                    icon: 'none'
                });
            }
        };

        // 表单验证
        const validateForm = () => {
            if (!formData.value.title.trim()) {
                uni.showToast({
                    title: '请输入作品标题',
                    icon: 'none'
                });
                return false;
            }

            if (!formData.value.category) {
                uni.showToast({
                    title: '请选择作品分类',
                    icon: 'none'
                });
                return false;
            }

            if (!formData.value.description.trim()) {
                uni.showToast({
                    title: '请输入作品描述',
                    icon: 'none'
                });
                return false;
            }

            if (!formData.value.image) {
                uni.showToast({
                    title: '请上传作品图片',
                    icon: 'none'
                });
                return false;
            }

            return true;
        };

        // ===== 返回数据和方法 =====
        return {
            // 响应式对象
            headerHeight,
            bottomHeight,
            formData,
            tagInput,
            showPreview,
            isSubmitting,
            userInfo,
            categoryOptions,

            // 方法函数
            handleHeaderHeightChange,
            handleBottomHeightChange,
            handleImageUploadClick,
            handleCategorySelectClick,
            handleAddTag,
            handleDeleteTag,
            handlePrivacyChange,
            handlePreviewToggle,
            handleSaveButtonClick,
            handleTabClick,
            loadEditData,
            validateForm
        };
    },
    // 组件之间交互事件
    methods: {

    },
    // 生命周期 - 创建完成（访问DOM元素）
    beforeCreate() {

    },
    // 生命周期 - 创建完成（访问当前this实例）
    created() {

    },
    // 生命周期 - 挂载完成（访问当前this实例）
    mounted() {

    },
    // 生命周期 - 更新之前（访问当前this实例）
    beforeUpdate() {

    },
    // 生命周期 - 更新之前（访问当前this实例）
    updated() {

    },
    // 生命周期 - 销毁之前（访问当前this实例）
    unmounted() {

    },
    // 生命周期 - 组件激活（访问当前this实例）
    activated() {

    },
    // 生命周期 - 组件停用（访问当前this实例）
    deactivated() {

    },
    // 生命周期 - 子孙组件错误时
    errorCaptured() {

    }
});
</script>
<style lang='less' scoped>
/* scoped 使用得定义的样式只在本页面内生效  */
.container {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-top: v-bind('headerHeight + "px"');
    padding-bottom: v-bind('bottomHeight + "px"');

    // 表单区域
    .form-section {
        margin: 20rpx;
        padding: 30rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

        // 图片上传区域
        .upload-section {
            margin-bottom: 30rpx;

            .upload-title {
                font-size: 30rpx;
                font-weight: bold;
                color: #333;
                margin-bottom: 15rpx;
            }

            .upload-area {
                width: 100%;
                height: 300rpx;
                border: 2rpx dashed #ddd;
                border-radius: 12rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #f8f8f8;

                .uploaded-image {
                    width: 100%;
                    height: 100%;
                    border-radius: 12rpx;
                }

                .upload-placeholder {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    color: #ccc;

                    .upload-text {
                        font-size: 26rpx;
                        margin-top: 10rpx;
                    }
                }
            }
        }

        // 表单组
        .form-group {
            margin-bottom: 30rpx;

            .form-label {
                font-size: 30rpx;
                font-weight: bold;
                color: #333;
                margin-bottom: 15rpx;
            }

            .form-input {
                width: 100%;
                height: 80rpx;
                padding: 0 20rpx;
                border: 1rpx solid #ddd;
                border-radius: 8rpx;
                font-size: 28rpx;
                color: #333;
                background-color: #fff;
            }

            .form-textarea {
                width: 100%;
                min-height: 200rpx;
                padding: 20rpx;
                border: 1rpx solid #ddd;
                border-radius: 8rpx;
                font-size: 28rpx;
                color: #333;
                background-color: #fff;
                line-height: 1.5;
            }

            .form-tip {
                font-size: 24rpx;
                color: #999;
                text-align: right;
                margin-top: 10rpx;
            }

            .category-selector {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 80rpx;
                padding: 0 20rpx;
                border: 1rpx solid #ddd;
                border-radius: 8rpx;
                background-color: #fff;

                .selected-category {
                    font-size: 28rpx;
                    color: #333;
                }
            }

            .tags-section {
                .tags-input {
                    margin-bottom: 15rpx;

                    .tag-input {
                        width: 100%;
                        height: 60rpx;
                        padding: 0 20rpx;
                        border: 1rpx solid #ddd;
                        border-radius: 8rpx;
                        font-size: 26rpx;
                        color: #333;
                        background-color: #fff;
                    }
                }

                .tags-list {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 15rpx;

                    .tag-item {
                        display: flex;
                        align-items: center;
                        padding: 8rpx 15rpx;
                        background-color: #007AFF;
                        border-radius: 20rpx;

                        .tag-text {
                            font-size: 24rpx;
                            color: #fff;
                            margin-right: 8rpx;
                        }

                        .tag-delete {
                            width: 24rpx;
                            height: 24rpx;
                            background-color: rgba(255, 255, 255, 0.3);
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        }
                    }
                }
            }

            .privacy-options {
                .privacy-item {
                    display: flex;
                    align-items: center;
                    margin-bottom: 15rpx;

                    .privacy-radio {
                        width: 30rpx;
                        height: 30rpx;
                        border: 2rpx solid #ddd;
                        border-radius: 50%;
                        margin-right: 15rpx;
                        position: relative;

                        &.active {
                            border-color: #007AFF;
                            background-color: #007AFF;

                            &::after {
                                content: '';
                                position: absolute;
                                top: 50%;
                                left: 50%;
                                transform: translate(-50%, -50%);
                                width: 12rpx;
                                height: 12rpx;
                                background-color: #fff;
                                border-radius: 50%;
                            }
                        }
                    }

                    .privacy-text {
                        font-size: 28rpx;
                        color: #333;
                    }
                }
            }
        }
    }

    // 预览区域
    .preview-section {
        margin: 20rpx;
        padding: 30rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

        .preview-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20rpx;

            .preview-title {
                font-size: 32rpx;
                font-weight: bold;
                color: #333;
            }

            .preview-toggle {
                font-size: 26rpx;
                color: #007AFF;
            }
        }

        .preview-content {
            .preview-work {
                border: 1rpx solid #f2f2f2;
                border-radius: 12rpx;
                overflow: hidden;

                .preview-image {
                    width: 100%;
                    height: 300rpx;
                }

                .preview-info {
                    padding: 20rpx;

                    .preview-title-text {
                        font-size: 32rpx;
                        font-weight: bold;
                        color: #333;
                        margin-bottom: 10rpx;
                    }

                    .preview-author {
                        font-size: 26rpx;
                        color: #666;
                        margin-bottom: 15rpx;
                    }

                    .preview-desc {
                        font-size: 28rpx;
                        color: #666;
                        line-height: 1.5;
                        margin-bottom: 15rpx;
                    }

                    .preview-tags {
                        display: flex;
                        flex-wrap: wrap;
                        gap: 10rpx;

                        .preview-tag {
                            padding: 6rpx 12rpx;
                            background-color: #f0f0f0;
                            border-radius: 15rpx;
                            font-size: 22rpx;
                            color: #666;
                        }
                    }
                }
            }
        }
    }

    // 操作按钮区域
    .action-section {
        margin: 20rpx;
        padding: 30rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

        .action-buttons {
            display: flex;
            gap: 20rpx;

            .preview-btn {
                flex: 1;
                height: 80rpx;
                background-color: #f8f8f8;
                color: #666;
                border: none;
                border-radius: 40rpx;
                font-size: 28rpx;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .save-btn {
                flex: 1;
                height: 80rpx;
                background-color: #007AFF;
                color: #ffffff;
                border: none;
                border-radius: 40rpx;
                font-size: 28rpx;
                font-weight: bold;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
    }
}
</style>